# -*- coding: utf-8 -*-
'''
    :file: app.py
    :author: -Farmer
    :url: https://blog.farmer233.top
    :date: 2022/05/05 15:49:15
'''
from cgi import FieldStorage
from io import BytesIO
from flask import Flask, render_template, request, send_file, url_for
from time import sleep
from flask_cors import CORS

app = Flask(__name__)

CORS(app=app)

app.static_folder = "imgs"


@app.route("/user", methods=['GET', 'POST'])
def user():
    name = request.args.get("user")
    user = request.form.get("user", "没有")
    fromJson = request.get_json()
    u = fromJson.get("u")
    s = render_template("index.html", user=u)
    print(s)
    return s



@app.post("/saveImg")
def handleIMG():
    imgFile = request.files['img']
    path = f"./imgs/{imgFile.filename}"
    imgFile.save(path)
    return {
        "path": path
    }

def IMGHandler(img) -> bytes:
    sleep(0.5)
    return img.stream.read()

@app.post("/tmpHandle")
def save_img():
    imgFile = request.files['img']
    # 处理图片 ... (花费 0.5 秒钟)
    resultIMG = IMGHandler(imgFile)
    return send_file(BytesIO(resultIMG), download_name=imgFile.filename, as_attachment=True)
